import * as express from 'express';
import * as logger from 'morgan';
import * as bodyParser from 'body-parser';
import { createProxyMiddleware } from 'http-proxy-middleware';
import { captureVideo } from './captureVideo';

const frontend = process.env['FRONT_ENDPOINT'] || 'http://localhost:3000';
const appPort = process.env['PORT'] || 3002;
const proxyPort = process.env['PROXY_PORT'] || 3003;

const app = express();
app.use(logger('dev'));
app.use(bodyParser.json({ limit: '50mb' }));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.post('/', (req, res, next) => {
  const { session } = req.body;
  const target = `http://localhost:${proxyPort}/tracks/${session}/capture`;
  // 因为浏览器安全限制，不是 https 的地址无法获取到 MediaDevices
  // 使用 express proxy 至 localhost 访问
  captureVideo(target);
  res.json('OK');
  return;
});

app.listen(appPort);

const proxyApp = express();
proxyApp.use(
  '/',
  createProxyMiddleware({
    target: frontend,
    changeOrigin: true
  })
);
proxyApp.listen(proxyPort);
